package gl.java.umsp.protocol;

import gl.java.umsp.Umsp;
import gl.java.umsp.UmspHeader;
import gl.java.umsp.bean.User;
import gl.java.umsp.router.ChannelRouter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GateWayHandleUserLogin implements IUmspHandler {
    @Override
    public boolean handle(final ChannelHandlerContext ctx, final UmspHeader msg)   {
        if (Umsp.CMD_LOGIN == msg.cmd) {
            final User u = new User(msg.userID, msg.gameID, String.valueOf(msg.userID));
            Channel oldConnect = ChannelRouter.getInstance().getChannel(msg.userID);
            if (oldConnect != null) {
                oldConnect.close();
                log.warn("![Repeat Login]! userID:" + u.userID);
                ChannelRouter.getInstance().unRegisterRouter(oldConnect);
            }
            registerRouter(ctx, msg, u);
            return true;
        }
        return false;
    }

    private void registerRouter(ChannelHandlerContext ctx, UmspHeader msg, User u) {
        ChannelRouter.getInstance().registerRouter(msg.userID, ctx.channel());
        Umsp.returnStringMsg(Umsp.CMD_LOGIN_RSP, u.toString(), ctx.channel());
    }
}
